/**
 * @description 首页 controller
 * @author malin
 */

const xss = require('xss')
const {
    creatBlog,
    getFollowersBlogList
} = require('../services/blog')
const {
    createBlogFailInfo
} = require('../model/ErrorInfo')
const { SuccessModel, ErrorModel } = require('../model/ResModel')
const { PAGE_SIZE, REG_FOR_AT_WHO } = require('../conf/constants')
const { getUserInfo } = require('../services/user')
const { createAtRelation } = require('../services/at-relation')

/**
 * 创建微博
 * @param {object} param0 创建微博所需要的数据 { userId, content, image }
 */
async function create ({ userId, content, image }) {

    // 分析并收集content中的用户
    // content：‘你也好 @李四 - lisi 你好 @王五 新人报道’
    const atUserNameList = []
    // 这个replace的目的不是替换，而是获取分组中的内容，即用户名
    content = content.replace(
        // 正则
        REG_FOR_AT_WHO,
        // 正则捕获回调
        (matchStr, nickName, userName) => {
            atUserNameList.push(userName)
            // 匹配的啥，就返回啥，不替换
            return matchStr
        }
    )

    // 根据@用户名，查询用户信息
    const atUserList = await Promise.all(
        // all: 参数是promise数组，所以getUserInfo前不加await
        atUserNameList.map(userName => getUserInfo(userName))
    )
    
    // 根据用户信息，获取用户ID
    const atUserIdList = atUserList.map(user => user.id)

    try {
        // service 创建微博
        const blog = await creatBlog({ userId, content: xss(content), image })
        // service 创建@关系（用户ID、微博ID）
        await Promise.all(atUserIdList.map(
            userId => createAtRelation(blog.id, userId)
        ))
        // 返回
        return new SuccessModel(blog)
    } catch(err) {
        console.error(err.message, err.stack)
        return new ErrorModel(createBlogFailInfo)
    }
}

/**
 * 获取首页微博列表
 * @param {number} userId 
 * @param {number} pageIndex 
 */
async function getHomeBlogList(userId, pageIndex = 0) {
    // service
    const result = await getFollowersBlogList({ userId, pageIndex, pageSize: PAGE_SIZE })
    const { count, blogList } = result
    return new SuccessModel({
        isEmpty: blogList.length === 0,
        blogList,
        pageSize: PAGE_SIZE,
        pageIndex,
        count 
    })
}

module.exports = {
    create,
    getHomeBlogList
}
